package com.ruoyi.cert.controller;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cert.domain.CertiXueshi;
import com.ruoyi.cert.service.ICertiXueshiService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

/**
 * 心理培训证书Controller
 *
 * @author duanxinli
 * @date 2024-03-13
 */
@RestController
@RequestMapping("/cert/xueshi")
public class CertiXueshiController extends BaseController {
    @Autowired
    private ICertiXueshiService certiXueshiService;

    /**
     * 查询心理培训证书列表
     */
    @PreAuthorize("@ss.hasPermi('cert:list')")
    @GetMapping("/list")
    public TableDataInfo list(CertiXueshi certiXueshi) {
        startPage();
        certiXueshi.getParams().put("userName", SecurityUtils.getUsername());
        List<CertiXueshi> list = certiXueshiService.selectCertiXueshiList(certiXueshi);
        return getDataTable(list);
    }

    /**
     * 导出心理培训证书列表
     */
    @PreAuthorize("@ss.hasPermi('cert:export')")
    @Log(title = "心理培训证书", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CertiXueshi certiXueshi) {
        List<CertiXueshi> list = certiXueshiService.selectCertiXueshiList(certiXueshi);
        ExcelUtil<CertiXueshi> util = new ExcelUtil<CertiXueshi>(CertiXueshi.class);
        util.exportExcel(response, list, "心理培训证书数据");
    }

    /**
     * 获取心理培训证书详细信息
     */
    @PreAuthorize("@ss.hasPermi('cert:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(certiXueshiService.selectCertiXueshiById(id));
    }

    /**
     * 新增心理培训证书
     */
    @PreAuthorize("@ss.hasPermi('cert:add')")
    @Log(title = "心理培训证书", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CertiXueshi certiXueshi) {
        return toAjax(certiXueshiService.insertCertiXueshi(certiXueshi));
    }

    /**
     * 修改心理培训证书
     */
    @PreAuthorize("@ss.hasPermi('cert:edit')")
    @Log(title = "心理培训证书", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CertiXueshi certiXueshi) {
        return toAjax(certiXueshiService.updateCertiXueshi(certiXueshi));
    }

    /**
     * 删除心理培训证书
     */
    @PreAuthorize("@ss.hasPermi('cert:remove')")
    @Log(title = "心理培训证书", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(certiXueshiService.deleteCertiXueshiByIds(ids));
    }


    @GetMapping(value = "/preview/{id}")
    @Anonymous
    @Log(title = "心理培训证书", businessType = BusinessType.OTHER)
    public ResponseEntity<byte[]> previewImage(@PathVariable("id") String id) throws IOException {
        CertiXueshi cert = certiXueshiService.selectCertiXueshiById(id);
        // 图片文件的路径，这里假设图片放在项目的resources/static/images目录下
        String filename = "cert2024.jpg";
        // 假设图片文件位于项目的resources/static目录下
        Resource resource = new ClassPathResource("static/images/" + filename);
        // 确保资源存在且可读
        if (!resource.exists() || !resource.isReadable()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        // 读取图片文件为BufferedImage
        BufferedImage bufferedImage = ImageIO.read(resource.getInputStream());
        // 添加名字
        addTextAndStamp(bufferedImage, cert);
        // 将BufferedImage转换为字节数组
        byte[] imageBytes = bufferedImageToByteArray(bufferedImage, "jpg"); // 或者使用 "jpg" 等其他格式
        // 设置响应头，指定Content-Type为图片类型
        String contentType = getContentType(filename);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(contentType));
        headers.setContentLength(imageBytes.length);
        // 返回图片作为响应体
        return ResponseEntity.ok()
                .headers(headers)
                .body(imageBytes);
    }

    public byte[] bufferedImageToByteArray(BufferedImage image, String format) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, format, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    // 根据图片文件扩展名获取对应的Content-Type
    private String getContentType(String imageName) {
        String contentType = "image/jpeg"; // 默认设置为JPEG
        String extension = imageName.substring(imageName.lastIndexOf(".") + 1).toLowerCase();
        switch (extension) {
            case "png":
                contentType = "image/png";
                break;
            case "gif":
                contentType = "image/gif";
                break;
            case "bmp":
                contentType = "image/bmp";
                break;
            // 可以添加更多图片格式的支持
            default:
                break;
        }
        return contentType;
    }

    public BufferedImage addTextAndStamp(BufferedImage image, CertiXueshi cert) throws IOException {
        Graphics2D g2d = image.createGraphics();

        // 设置字体
        Font font = new Font("SimKai", Font.BOLD, 25);
        g2d.setFont(font);
        // 设置文字颜色
        g2d.setColor(Color.black);
        // 打名字
        g2d.drawString(cert.getName(), 150, 250);

        // 设置编码字体
        Font codeFont = new Font("SimHei", Font.BOLD, 22);
        g2d.setFont(codeFont);
        // 设置文字颜色
        g2d.setColor( new Color(52, 91, 122));
        // 打编号
        g2d.drawString(cert.getCode(), 162, 100);
        // 释放图形上下文使用的系统资源
        g2d.dispose();

        return image;
    }
}
